package com.mainbo.androidframework.utils;

import java.security.MessageDigest;

public class MD5 {
   public static int LONG_TYPE = 32; //32位加密
   public static int SHORT_TYPE = 16; //16位加密
   private final static String[] UppercaseHex = { "0", "1", "2", "3", "4", "5",
		"6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
   private final static String[] LowerHex = { "0", "1", "2", "3", "4", "5",
 		"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
   
   	/**
	 * MD5加密字符串
	 * 
	 * @param str
	 *            被加密的字符串
	 * @return
	 */
	public static String encodeString(String str) {
		return encodeString(str, LONG_TYPE, true);
	}

	/**
	 * MD5加密字符串
	 * 
	 * @param str
	 *            被加密的字符串
	 * @param length
	 *            加密输出长度
	 * @param lowCase
	 *            输出大小写限制
	 * @return
	 */
   public static String encodeString(String str, int length, boolean lowCase) {
	   String encodeStr = "";
	   if (str == null) {
		   return encodeStr;
	   }
	   
	   try {
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] digestByte = md.digest(str.getBytes("UTF-8"));
		encodeStr = byteArrayToHexString(digestByte, lowCase);
		if (length == SHORT_TYPE) {
			encodeStr = encodeStr.substring(8, 24);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	   return encodeStr;
   }
   
	private static String byteArrayToHexString(byte[] b, boolean lowerCase) {
	    StringBuffer resultSb = new StringBuffer();
	    for (int i = 0; i < b.length; i++) {
	      resultSb.append(byteToHexString(b[i], lowerCase));
	    }
	    return resultSb.toString();
	  }
	
	private static String byteToHexString(byte b, boolean lowerCase) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		if (lowerCase) {
			return LowerHex[d1] + LowerHex[d2];
		} else {
			return UppercaseHex[d1] + UppercaseHex[d2];
		}
		
	}
}
